package com.hzit.config;

import com.hzit.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
	private MyUserDetailService userDetailService;
	@Autowired
	private DataSource dataSource;
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.exceptionHandling()
				.accessDeniedPage("/unauth.html")   //授权失败页面
			 .and()
			 .formLogin()
		     .loginPage("/login.html")          // 登录页
			 .loginProcessingUrl("/login")      // 登录处理页
		     .successForwardUrl("/user/welcome")   // 登录成功后跳转的页面,需要post请求
			 .and()
			 .authorizeRequests()
			 //1. 拥有user权限的用户才能访问/user/list这个请求资源
			 // .antMatchers("/user/list").hasAuthority("user")
			 //2. 拥有user或admin或userXXX三个权限的任意一种就可访问/user/list
			 //  .antMatchers("/user/list").hasAnyAuthority("user","admin","userxxx")
			 //3. 拥有manager角色，只能访问/user/list这个资源
			 // .antMatchers("/user/list").hasRole("manager")	 // ROLE_manager
			 //4. 拥有manager或chairman其中之一，才能访问/user/list资源
			 // .antMatchers("/user/list").hasAnyRole("manager","chairman")
			 .antMatchers("/webjars/**","/login.html")
			 .permitAll()	                    // 上面的无须授权即可访问
			 .anyRequest()                      // 任何其它请求
			 .authenticated()                   // 都要认证才能访问
			//5. rememberMe功能实现
			 .and()
			 .rememberMe()
			 .tokenValiditySeconds(300)         // cookie的到期时间
			 .rememberMeParameter("rememberMe")	// 设置rememberMe的参数名
			 .userDetailsService(userDetailService)
			 .tokenRepository(tokenRepository())
			//6. 防止跨域请求伪造
			 .and()
			 .csrf()
			 .disable();
	}
	@Bean               // 一定要放在spring容器中
	public PersistentTokenRepository tokenRepository() {
		JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
		jdbcTokenRepository.setDataSource(dataSource);      // 设置数据源
		jdbcTokenRepository.setCreateTableOnStartup(true);  // 设置启动时自动生成表结构
		return jdbcTokenRepository;
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailService).passwordEncoder(encoder());
	}

	@Bean
	public BCryptPasswordEncoder encoder(){
		return new BCryptPasswordEncoder();
	}

	public static void main(String[] args) {
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		String encode = encoder.encode("123");
		System.out.println("encode = " + encode);

	}
}
